package org.visionlibrary.image.filters.histogram;

import javax.media.jai.TiledImage;

import org.visionlibrary.image.acquisition.ImageFactory;
import org.visionlibrary.image.model.AbstractFilter;
import org.visionlibrary.image.model.FilterTools;


public class SimpleHistogramEqualization extends AbstractFilter {
	@Override
	public TiledImage applyFilter(TiledImage src, TiledImage dest) {
		if (null == src)
			throw new NullPointerException("Source image is null.");

		if (null == dest)
			dest = (new ImageFactory()).createCompatibleImage(src);

		int maxX = src.getWidth();
		int maxY = src.getHeight();
		for (int ch = 0; ch < src.getNumBands(); ch++) {
			int[] histogram = FilterTools.getCumulativeHistogram(src, ch);
			double alpha = (double)histogram.length / (double)(maxX*maxY);
			
			for (int x = 0; x < maxX; x++)
				for (int y = 0; y < maxY; y++) {
					int pixel = src.getSample(x, y, ch);
					pixel = (int)(histogram[pixel] * alpha);
					dest.setSample(x, y, ch, pixel);
				}
		}

		return dest;
	}
}
